﻿using Casamiel.API.Application.Commands;
using Casamiel.API.Application.Models;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.API.Infrastructure.Middlewares;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Domain;
using Casamiel.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using MediatR;
using Casamiel.API.Application;
using Casamiel.Domain.Request;

namespace Casamiel.API.Controllers.V1
{
    /// <summary>
    /// 
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/Login")]//{api-version:apiVersion}
    [Authorize]
    [ApiController]
    //[ApiVersionNeutral]
    public class LoginController : ControllerBase
    {
        private readonly IMobileCheckCode _mobileCheckCode;
        private readonly IIcApiService _iicApiService;
        private readonly IMemberService _memberService;
        private readonly IMemberCardService _memberCard;
        //private readonly ICasamielIntegrationEventService _casamielIntegrationEventService;
        //private readonly CasamielContext _context;
        private readonly ICacheService _cacheService;
        private readonly IUserLogService _userLog;
        //private readonly NLog.ILogger logger = LogManager.GetLogger("BizInfo");
        private readonly ITokenProvider _tokenProvider;
        private readonly IMediator _mediator;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iicApiService"></param>
        /// <param name="mobileCheckCode"></param>
        /// <param name="memberRepository"></param>
        /// <param name="memberCard"></param>
        /// <param name="cacheService"></param>
        /// <param name="userLog"></param>
        /// <param name="tokenProvider"></param>
        /// <param name="mediator"></param>
        public LoginController(
            IIcApiService iicApiService,
            IMobileCheckCode mobileCheckCode,
            IMemberService memberRepository,
            IMemberCardService memberCard,
            //ICasamielIntegrationEventService casamielIntegrationEventService,
            //CasamielContext context,
            ICacheService cacheService,
            IUserLogService userLog,
            ITokenProvider tokenProvider,
        IMediator mediator)
        {
            _iicApiService = iicApiService;
            _mobileCheckCode = mobileCheckCode;
            _memberCard = memberCard;
            _memberService = memberRepository;
            _userLog = userLog;
            _cacheService = cacheService;
            _tokenProvider = tokenProvider;
            _mediator = mediator;
        }
        /// <summary>
        /// 新接口，会员token刷新
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckLoginAttribute))]
        public async Task<IActionResult> RefreshUserToken(
        [FromBody] UserTokenDto data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            if (string.IsNullOrEmpty(token)) {
                return Ok(new { code = -1, msg = "登录凭证已过期，请重新登陆" });
            }
            int loginType = 1;
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            loginType = userAgent.Contains("CASAMIEL", StringComparison.OrdinalIgnoreCase) ? 1 : 2;
            if (userAgent.Contains("MicroMessenger", StringComparison.OrdinalIgnoreCase)) {
                loginType = 3;//微信端
            }
            try {
                var handler = new JwtSecurityTokenHandler();
                JwtSecurityToken dtoken = handler.ReadJwtToken(token);
                var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, RSAHelper.privateKey, RSAHelper.publicKey);

                var exp = dtoken.Payload.Exp;
                string mobile = rsa.Decrypt(dtoken.Payload.Jti);
                //  Console.WriteLine(new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds());
                if (exp < new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()) {
                    var a = new { code = -1, msg = "登录凭证已过期，请重新登陆" };

                    return new JsonResult(a);
                }
                //var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("cssupersecret_secretke!miel"));
                //TokenProviderOptions _tokenOptions = new TokenProviderOptions
                //{
                //    Audience = "casamiel",
                //    Issuer = "CasamielIssuer",
                //    SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
                //};
                //var tpm = new TokenProvider(_tokenOptions);
                // var tokens = _tokenProvider.GenerateToken(mobile);
                //JWTTokenOptions _tokenOptions = new JWTTokenOptions();
                //var audience = "casamiel";
                //DateTime expire = DateTime.Now.AddDays(60);
                //string jti = Jti;// + expire.GetMilliseconds();
                //jti = rsa.Encrypt(jti);//jti.GetMd5();
                //var claims = new[]
                //{
                // new Claim(ClaimTypes.Role,""),
                //new Claim(ClaimTypes.NameIdentifier,Jti, ClaimValueTypes.Integer32),
                //new Claim("jti",jti,ClaimValueTypes.String)
                //};
                //ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(Jti, "TokenAuth"), claims);
                //var newtoken = handler.CreateEncodedJwt(new SecurityTokenDescriptor
                //{
                //    Issuer = "CasamielIssuer",
                //    Audience = audience,
                //    SigningCredentials = _tokenOptions.Credentials,
                //    Subject = identity,
                //    Expires = expire,
                //});
                //var response = new TokenEntity
                //{
                //    access_token = newtoken,
                //    expires_in = (int)TimeSpan.FromDays(15).TotalSeconds
                //};

                var command = new CreateMemberAccessTokenComand(mobile, loginType, data.registration_Id) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
                var tokens = await _mediator.Send(command).ConfigureAwait(false);

                var member = await _memberService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
                var memberdata = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email };
                return Ok(new { code = 1, data = tokens, member = memberdata });
            } catch (ArgumentException) {

                return new JsonResult(new { code = -1, msg = "登录凭证无效" });
            }
        }
        /// <summary>
        /// 得到新token
        /// </summary>
        /// <param name="token"></param>
        /// <param name="registration_Id"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckLoginAttribute))]
        public async Task<IActionResult> Refreshtoken([FromHeader(Name = "u-token")] string token, string registration_Id)
        {
            var userAgent = Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.OrdinalIgnoreCase) == true ? 1 : 2;
            try {
                var handler = new JwtSecurityTokenHandler();
                JwtSecurityToken dtoken = handler.ReadJwtToken(token);
                var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, RSAHelper.privateKey, RSAHelper.publicKey);

                var exp = dtoken.Payload.Exp;
                string Jti = rsa.Decrypt(dtoken.Payload.Jti);
                //Console.WriteLine(Jti);
                //Console.WriteLine(exp);
                //Console.WriteLine(new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds());
                //if (exp<  new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds())
                //{
                //    Console.WriteLine("过期");
                //    return NotFound();
                //}
                JWTTokenOptions _tokenOptions = new JWTTokenOptions();
                var audience = "casamiel";
                DateTime expire = DateTime.Now.AddDays(15);
                string jti = Jti;// + expire.GetMilliseconds();
                jti = rsa.Encrypt(jti);//jti.GetMd5();
                var claims = new[]
                {
                 new Claim(ClaimTypes.Role,""),
                new Claim(ClaimTypes.NameIdentifier,Jti, ClaimValueTypes.Integer32),
                new Claim("jti",jti,ClaimValueTypes.String)
            };
                ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(Jti, "TokenAuth"), claims);
                var newtoken = handler.CreateEncodedJwt(new SecurityTokenDescriptor {
                    Issuer = "CasamielIssuer",
                    Audience = audience,
                    SigningCredentials = _tokenOptions.Credentials,
                    Subject = identity,
                    Expires = expire
                });
                var response = new TokenEntity {
                    access_token = newtoken,
                    expires_in = (int)TimeSpan.FromDays(15).TotalSeconds
                };
                var m = await _memberService.FindAsync<ICasaMielSession>(Jti, loginType).ConfigureAwait(false);
                if (m != null) {
                    m.Access_Token = newtoken;
                    m.UpdateTime = DateTime.Now;
                    m.Login_Count++;
                    m.Expires_In = response.expires_in;
                    m.Resgistration_Id = registration_Id;
                    await _memberService.UpdateAsync<ICasaMielSession>(m).ConfigureAwait(false);
                    // await _memberAccessTokenRespository.UnitOfWork.SaveChangesAsync();
                } else {
                    m = new MemberAccessToken {
                        Access_Token = newtoken,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        Login_Count = 1,
                        Login_Type = loginType,
                        Mobile = Jti,
                        Expires_In = response.expires_in
                        ,
                        Resgistration_Id = registration_Id
                    };
                    await _memberService.AddAsync<ICasaMielSession>(m).ConfigureAwait(false);
                }
                return new JsonResult(response);
            } catch (ArgumentException) {

                return NotFound();
            }
        }

        /// <summary>
        ///获取手机验证码
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        //[Route("[action]")]
        [Route("[action]")]
        public async Task<IActionResult> GetCheckCode(string mobile)
        {
            if (string.IsNullOrEmpty(mobile)) {
                return new JsonResult(new { code = -1, msg = "手机号不能为空" });
            }

            var msg = await _mobileCheckCode.SendCheckCodeAsync(mobile).ConfigureAwait(false);
            if (string.IsNullOrEmpty(msg)) {
                return new JsonResult(new { code = 1, msg = "验证码已发送" });
            }
            return new JsonResult(new { code = -1, msg = msg });
        }
        /// <summary>
        /// 手机验证码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        /// <remarks>
        /// {"mobile":"xxxxxxxxx"}
        /// </remarks>
        [HttpPost]
        //[Route("[action]")]
        [Route("[action]")]
        public async Task<IActionResult> GetSmsCode([FromBody] GetSmsCodeRequest data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            //if (string.IsNullOrEmpty(data["mobile"].ToString())) {
            //    return new JsonResult(new { code = -1, msg = "手机号不能为空" });
            //}
            string mobile = data.Mobile;
            if (string.IsNullOrEmpty(mobile)) {
                return new JsonResult(new { code = -1, msg = "手机号不能为空" });
            }

            var msg = await _mobileCheckCode.SendCheckCodeAsync(mobile).ConfigureAwait(false);
            if (string.IsNullOrEmpty(msg)) {
                return new JsonResult(new { code = 0, msg = "验证码已发送" });
            }
            return new JsonResult(new { code = -1, msg = msg });
        }

        /// <summary>
        /// 获取已经注册的手机验证码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        //[Route("[action]")]
        [Route("[action]")]
        public async Task<IActionResult> GetLoginSmsCode([FromBody] GetSmsCodeRequest data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            //if (string.IsNullOrEmpty(data["mobile"].ToString())) {
            //    return new JsonResult(new { code = -1, msg = "手机号不能为空" });
            //}
            string mobile = data.Mobile;

            var member = await _memberService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (member == null) {
                return new JsonResult(new { code = -2, msg = "请先注册" });
            }
            var msg = await _mobileCheckCode.SendCheckCodeAsync(mobile).ConfigureAwait(false);
            if (string.IsNullOrEmpty(msg)) {
                return new JsonResult(new { code = 0, msg = "验证码已发送" });
            }
            return new JsonResult(new { code = -1, msg = msg });
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <param name="token">用户token</param>
        /// <returns></returns>
        [HttpPost]
        [HttpGet]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckLoginAttribute))]
        public async Task<IActionResult> Logout([FromHeader(Name = "u-token")] string token)
        {
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["User-Agent"].ToString() : Request.Headers["UserAgent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.CurrentCultureIgnoreCase) ? 1 : 2;
            if (userAgent.Contains("MicroMessenger", StringComparison.CurrentCultureIgnoreCase)) {
                loginType = 3;
            }

            var mobile = MemberHelper.GetMobile(token);
            var logoutcommand = new LogoutCommand(mobile, loginType) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            await _mediator.Send(logoutcommand).ConfigureAwait(false);

            //var mtoken = await _memberService.FindAsync<ICasaMielSession>(mobile, loginType);
            //if (mtoken != null)
            //{
            //    mtoken.Access_Token = "";
            //    await _memberService.UpdateAsync<ICasaMielSession>(mtoken);
            //    //await _memberAccessTokenRespository.UnitOfWork.SaveChangesAsync();
            //}
            //string key = Constant.TOKEN_PREFIX + mobile + "_" + loginType;
            //_cacheService.Remove(key);
            //var logdata = new UserLog { Url = Request.GetAbsoluteUri(), OPInfo = "会员注销", OPTime = DateTime.Now, UserName = mobile, UserIP = Request.GetUserIp() };
            //await _userLog.AddAsync<ICasaMielSession>(logdata);
            return new JsonResult(new { code = 1, msg = "注销成功！" });
        }

        /// <summary>
        ///获取登陆手机验证码
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetLoginCheckCode(string mobile)
        {
            var member = await _memberService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (member == null) {
                return new JsonResult(new { code = -2, msg = "请先注册" });
            }
            var msg = await _mobileCheckCode.SendCheckCodeAsync(mobile).ConfigureAwait(false);
            if (string.IsNullOrEmpty(msg)) {
                return new JsonResult(new { code = 1, msg = "验证码已发送" });
            }
            return new JsonResult(new { code = -1, msg = msg });
        }
        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        //[Route("[action]")]
        [Route("[action]")]
        public async Task<IActionResult> Login([FromBody]LoginReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);

            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.CurrentCulture) ? 1 : 2;

            if (userAgent.Contains("MicroMessenger", StringComparison.CurrentCulture)) {
                loginType = 3;

            }


            var member = await _memberService.FindAsync<ICasaMielSession>(data.Mobile).ConfigureAwait(false);
            if (member == null) {
                return new JsonResult(new { code = "-2", msg = "请先注册" });
            }

            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(data.Mobile, data.Yzm, true).ConfigureAwait(false);

            if (sucess["code"].ToString() != "0") {
                return new JsonResult(new { code = "-1", msg = sucess["msg"].ToString() });
            }
            var loginCommand = new LoginCommand { Mobile = data.Mobile, LoginType = loginType, Registration_Id = data.Registration_Id, Source = 1, RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var result = await _mediator.Send(loginCommand).ConfigureAwait(false);

            var memberdata = new { Mobile = member.Mobile, Nick = member.Nick, Birthday = member.Birthday, Sex = member.Sex, TrueName = member.TrueName, Email = member.Email, cardno = result.Item3 };
            return new JsonResult(new { code = 1, data = result.Item2, member = memberdata });
        }
        /// <summary>
        /// 注册会员申请虚拟卡
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> RegIcselfregist([FromBody] RegIcselfregistReq data)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            ConsoleHelper.DoLog(data, Request);
            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(data.Mobile, data.Yzm, true).ConfigureAwait(false);
            if (sucess["code"].ToString() != "0") {
                return new JsonResult(new { code = -1, msg = sucess["msg"].ToString() });
            }
            var source = 0;
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.CurrentCulture) ? 1 : 2;
            if (loginType == 1) {
                source = 1;
            }
            if (userAgent.Contains("MicroMessenger", StringComparison.CurrentCulture)) {
                loginType = 3;//微信端
                source = 2;
            }

            var entity = await _memberService.FindAsync<ICasaMielSession>(data.Mobile).ConfigureAwait(false);
            if (entity != null) {
                return new JsonResult(new { code = -2, msg = "手机号已注册，请登录" });
            }
            //_cacheService.Remove(Constant.MYCARDS_PREFIX + data.Mobile);
            var newcard = await _iicApiService.Icselfregist(data.Mobile, 15).ConfigureAwait(false);
            if (newcard.code == 0) {
                var jobj = JsonConvert.DeserializeObject<JObject>(newcard.content);
                var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"新用户注册会员卡，卡号[{jobj["cardno"].ToString()}]", OPTime = DateTime.Now, UserName = data.Mobile, UserIP = Request.GetUserIp() };
                await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);

                if (entity == null) {
                    entity = new Member { Mobile = data.Mobile, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now, Source = source };
                    await _memberService.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                } else {
                    entity.LastLoginDate = DateTime.Now;
                    await _memberService.UpdateLastLoginDateAsync<ICasaMielSession>(entity.ID, DateTime.Now).ConfigureAwait(false);
                    //await _memberService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                }

                var command = new CreateMemberAccessTokenComand(data.Mobile, loginType, data.Registration_Id) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
                var result = await _mediator.Send(command).ConfigureAwait(false);

                var mcard = new MemberCard();
                mcard.M_ID = entity.ID;

                mcard.CardNO = jobj["cardno"].ToString();
                mcard.Mobile = data.Mobile;
                mcard.IsBind = true;
                mcard.CardType = "2";
                mcard.BindTime = DateTime.Now;
                mcard.CreateTime = DateTime.Now;
                mcard.Source = 15;
                await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);
                var memberdata = new { Mobile = entity.Mobile, Nick = entity.Nick, Birthday = entity.Birthday, Sex = entity.Sex, TrueName = entity.TrueName, Email = entity.Email, cardno = mcard.CardNO };
                return Ok(new { code = 1, data = result, member = memberdata });
            }

            return Ok(new { code = newcard.code, content = newcard.content, msg = newcard.msg });
        }
        /// <summary>
        /// 注册会员并绑卡
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> RegBindCard([FromBody] RegBindCardReq data)
        {
            ConsoleHelper.DoLog(data, Request);
            var source = 0;
            var userAgent = string.IsNullOrEmpty(Request.Headers["User-Agent"].ToString()) ? Request.Headers["UserAgent"].ToString() : Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.CurrentCulture) ? 1 : 2;
            if (loginType == 1) {
                source = 1;
            }
            if (userAgent.Contains("MicroMessenger", StringComparison.CurrentCulture)) {
                loginType = 3;
                source = 2;
            }
            var sucess = await _mobileCheckCode.CheckSmsCodeAsync(data.Mobile, data.Yzm, true).ConfigureAwait(false);
            if (sucess["code"].ToString() != "0") {
                return new JsonResult(new { code = "-1", msg = sucess["msg"].ToString() });
            }
           // _cacheService.Remove(Constant.MYCARDS_PREFIX + data.Mobile);
            var entity = await _memberService.FindAsync<ICasaMielSession>(data.Mobile).ConfigureAwait(false);
            var mcards = await _memberCard.GetListAsync<ICasaMielSession>(data.Mobile).ConfigureAwait(false);

            var bandcard = await _iicApiService.Icregist(data.Cardno, data.Mobile, 15).ConfigureAwait(false);
            if (bandcard != null) {
                if (bandcard.code == 0 || bandcard.code == 101 || bandcard.code == 8) {
                    if (entity == null) {
                        entity = new Member { Mobile = data.Mobile, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now, Source = source };
                        await _memberService.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);

                        var mcard = new MemberCard {
                            CardNO = data.Cardno,
                            CardType = "1",
                            Mobile = data.Mobile,
                            IsBind = true,
                            BindTime = DateTime.Now,
                            CreateTime = DateTime.Now,
                            Source = 15
                        };
                        await _memberCard.AddAsync<ICasaMielSession>(mcard).ConfigureAwait(false);


                        var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"新用户注册绑卡，卡号[{data.Cardno}]", OPTime = DateTime.Now, UserName = data.Mobile, UserIP = Request.GetUserIp() };
                        await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                    } else {
                        var list = mcards.Where(a => a.IsBind == true && a.CardType != "3").ToList();
                        if (list.Count() > 0) {
                            if (list.Where(c => c.CardNO == data.Cardno).Count() == 1) {
                                goto resutl;
                            }
                            return new JsonResult(new { code = "-1", msg = "您已经绑过卡" });
                        }
                        var mc = mcards.Where(c => c.CardNO == data.Cardno).FirstOrDefault();
                        if (mc == null) {
                            mc = new MemberCard();
                            mc.CardNO = data.Cardno;
                            mc.Mobile = data.Mobile;
                            mc.IsBind = true;
                            mc.CardType = "1";
                            mc.BindTime = DateTime.Now;
                            mc.CreateTime = DateTime.Now;
                            mc.Source = 15;
                            await _memberCard.AddAsync<ICasaMielSession>(mc).ConfigureAwait(false);

                            var logdata = new UserLog { Url = Request.GetShortUri(), OPInfo = $"新用户注册绑卡，卡号[{data.Cardno}]", OPTime = DateTime.Now, UserName = data.Mobile, UserIP = Request.GetUserIp() };
                            await _userLog.AddAsync<ICasaMielSession>(logdata).ConfigureAwait(false);
                        } else {
                            mc.IsBind = true;
                            mc.BindTime = DateTime.Now;
                            await _memberCard.UpdateAsync<ICasaMielSession>(mc).ConfigureAwait(false);
                        }
                    }
                } else {
                    return new JsonResult(new { code = "-1", msg = bandcard.msg });
                }
            }

        resutl:

            if (entity != null) {
                entity.LastLoginDate = DateTime.Now;
                await _memberService.UpdateLastLoginDateAsync<ICasaMielSession>(entity.ID, DateTime.Now).ConfigureAwait(false);
                //await _memberService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                //await _memberRepository.UnitOfWork.SaveChangesAsync();
            }

            var command = new CreateMemberAccessTokenComand(data.Mobile, loginType, data.Registration_Id) { RequestUrl = Request.GetShortUri(), UserIP = Request.GetUserIp() };
            var token = await _mediator.Send(command).ConfigureAwait(false);

            var memberdata = new { Mobile = entity.Mobile, Nick = entity.Nick, Birthday = entity.Birthday, Sex = entity.Sex, TrueName = entity.TrueName, Email = entity.Email, cardno = data.Cardno };
            return Ok(new { code = 1, data = token, member = memberdata });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="yzm">验证码</param>
        /// <param name="registration_Id">机器码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetTokenAsync(string mobile, string yzm, string
            registration_Id)
        {
            //MemberDto member = new MemberDto { mobile = mobile, yzm = yzm, registration_Id = registration_Id };
            //ConsoleHelper.DoLog(member, Request);
            var sucess = _mobileCheckCode.CheckCode(mobile, yzm, false);
            if (sucess["Success"].ToString().ToLower() == "false") {
                return new JsonResult(new { code = "-1", msg = sucess["msg"].ToString() });
            }

            JWTTokenOptions _tokenOptions = new JWTTokenOptions();
            var audience = "casamiel";
            DateTime expire = DateTime.Now.AddDays(15);
            var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, RSAHelper.privateKey, RSAHelper.publicKey);
            var handler = new JwtSecurityTokenHandler();
            string jti = mobile;// + expire.GetMilliseconds();
            jti = rsa.Encrypt(jti);//jti.GetMd5();
            var claims = new[]
            {
                 new Claim(ClaimTypes.Role,""),
                new Claim(ClaimTypes.NameIdentifier,mobile, ClaimValueTypes.Integer32),
                new Claim("jti",jti,ClaimValueTypes.String)
            };
            ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(mobile, "TokenAuth"), claims);
            var token = handler.CreateEncodedJwt(new SecurityTokenDescriptor {
                Issuer = "CasamielIssuer",
                Audience = audience,
                SigningCredentials = _tokenOptions.Credentials,
                Subject = identity,
                Expires = expire
            });

            var entity = await _memberService.FindAsync<ICasaMielSession>(mobile).ConfigureAwait(false);
            if (entity == null) {
                entity = new Member { Mobile = mobile, CreateDate = DateTime.Now, LastLoginDate = DateTime.Now };
                await _memberService.AddAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                //await _memberRepository.UnitOfWork.SaveEntitiesAsync();

                //entity = new Application.Models.Member { Mobile = mobile, Birthday=DateTime.Parse("1/1/1753 12:00:01"), Sex=-1, CreateDate = DateTime.Now,LastLoginDate=DateTime.Now};

                //var su = await _member.AddMemberAync(entity);
                //if (su != 1)
                //{
                //    return new JsonResult(new { code = -1, msg = "登陆失败" });
                //}
            } else {
                entity.LastLoginDate = DateTime.Now;
                await _memberService.UpdateLastLoginDateAsync<ICasaMielSession>(entity.ID, DateTime.Now).ConfigureAwait(false);
                //await _memberService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
            }
            var userAgent = Request.Headers["User-Agent"].ToString();
            int loginType = userAgent.Contains("CASAMIEL", StringComparison.CurrentCulture) == true ? 1 : 2;

            var response = new TokenEntity {
                access_token = token,
                expires_in = (int)TimeSpan.FromDays(15).TotalSeconds
            };
            var m = await _memberService.FindAsync<ICasaMielSession>(mobile, loginType).ConfigureAwait(false);
            if (m != null) {
                m.Access_Token = token;
                m.UpdateTime = DateTime.Now;
                m.Login_Count++;
                m.Expires_In = response.expires_in;
                m.Resgistration_Id = registration_Id;
                await _memberService.UpdateAsync<ICasaMielSession>(m).ConfigureAwait(false);
            } else {
                m = new MemberAccessToken {
                    Access_Token = token,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    Login_Count = 1,
                    Login_Type = loginType,
                    Mobile = mobile,
                    Expires_In = response.expires_in,
                    Resgistration_Id = registration_Id
                };
                await _memberService.AddAsync<ICasaMielSession>(m).ConfigureAwait(false);
            }
            return new JsonResult(new { code = 1, data = response });
        }


    }
}